package com.igeek.web;

import com.igeek.domain.User;
import com.igeek.service.UserService;
import com.igeek.utils.CommonUtils;
import com.igeek.utils.MD5Utils;
import com.igeek.utils.MailUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;
import java.util.Random;
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    public void login(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        String code=request.getParameter("code");
        String sessionCode=(String)request.getSession().getAttribute("code_session");
        if(!sessionCode.equals(code)){
            request.setAttribute("msg","验证码不正确!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

        User user=new User();
        try {
            BeanUtils.populate(user,request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(user);
        Cookie[] cookies=request.getCookies();
        boolean flag=false;
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if("password".equals(cookie.getName())){
                    flag=true;
                    break;
                }
            }
        }
        if(!flag){
            String md5Pwd= MD5Utils.md5(user.getPassword());
            user.setPassword(md5Pwd);
        }

        UserService userService=new UserService();
        User existUser=userService.login(user);
        if(existUser.getState()==0){
            request.setAttribute("msg","该用户还未激活,请先到邮箱取激活!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        if(existUser==null){
            request.setAttribute("msg","用户名或者密码不正确!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        //登录成功
        //存储用户的信息
        HttpSession session=request.getSession();
        session.setAttribute("user",existUser);
        //记住用户名
        String rememberName=request.getParameter("rememberName");
        if("on".equals(rememberName)){
            //把用户名存储在客户端
            Cookie cookie=new Cookie("username",user.getUsername());
            cookie.setMaxAge(24*60*60*365);
            cookie.setPath("/");
            response.addCookie(cookie);
        }else{
            Cookie cookie=new Cookie("username","");
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }

        //自动登录
        String autoLogin=request.getParameter("autoLogin");
        if("on".equals(autoLogin)){
            //把用户名存储在客户端
            Cookie nameCookie=new Cookie("autousername",user.getUsername());
            nameCookie.setMaxAge(24*60*60*365);
            nameCookie.setPath("/");
            response.addCookie(nameCookie);


            Cookie pwdCookie=new Cookie("password",user.getPassword());
            pwdCookie.setMaxAge(24*60*60*365);
            pwdCookie.setPath("/");
            response.addCookie(pwdCookie);
        }else{
            //把用户名存储在客户端
            Cookie nameCookie=new Cookie("autousername","");
            nameCookie.setMaxAge(0);
            nameCookie.setPath("/");
            response.addCookie(nameCookie);


            Cookie pwdCookie=new Cookie("password","");
            pwdCookie.setMaxAge(0);
            pwdCookie.setPath("/");
            response.addCookie(pwdCookie);
        }
        //回到首页
        response.sendRedirect("index.jsp");

    }

    public void register(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        String code=request.getParameter("code");
        String sessionCode=(String) request.getSession().getAttribute("code_session");
        if(!sessionCode.equals(code)){
            request.setAttribute("msg","验证码不正确!");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        User user=new User();
        Map<String,String[]> map=request.getParameterMap();
        //处理string-->date
        ConvertUtils.register(new DateLocaleConverter(), Date.class);
        try {
            BeanUtils.populate(user,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setUid(CommonUtils.getUUID());
        String activeCode=CommonUtils.getUUID();
        user.setCode(activeCode);
        //默认用户的激活状态，默认是未激活状态
//        user.setState(0);
        UserService userService=new UserService();
        boolean result=userService.register(user);
        if(result){
            String emailMsg = "恭喜您注册成功，请点击下面的连接进行激活账户"
                    + "<a href='http://localhost:8088/igeekShop/user?method=active&&activeCode="+activeCode+"'>"
                    +"http://localhost:8088/igeekShop/user?method=active&&activeCode="+activeCode+"</a>";;
            try {
                MailUtils.sendMail(user.getEmail(), emailMsg);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            response.sendRedirect("registerSuccess.jsp");
        }
    }

    /**
     * 激活
     * @param request
     * @param response
     * @throws IOException
     */
    public  void active(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String activeCode=request.getParameter("activeCode");
        UserService service = new UserService();
        service.active(activeCode);
        response.sendRedirect("login.jsp");
    }

    /**
     * 验证码
     * @param request
     * @param response
     * @throws IOException
     */
    public void checkcode(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //  创建画布
        int width = 120;
        int height = 40;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //  获得画笔
        Graphics g = bufferedImage.getGraphics();
        //  填充背景颜色
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        //  绘制边框
        g.setColor(Color.red);
        g.drawRect(0, 0, width - 1, height - 1);
        //  生成随机字符
        //  准备数据
        String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        //  准备随机对象
        Random r = new Random();
        //  声明一个变量 保存验证码
        String code = "";
        //  书写4个随机字符
        for (int i = 0; i < 4; i++) {
            //  设置字体
            g.setFont(new Font("宋体", Font.BOLD, 28));
            //  设置随机颜色
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

            String str = data.charAt(r.nextInt(data.length())) + "";
            g.drawString(str, 10 + i * 28, 30);

            //  将新的字符 保存到验证码中
            code = code + str;
        }
        //  绘制干扰线
        for (int i = 0; i < 6; i++) {
            //  设置随机颜色
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }

        //  将验证码 打印到控制台
        System.out.println(code);

        //  将验证码放到session中
        request.getSession().setAttribute("code_session", code);

        //  将画布显示在浏览器中
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

    public void checUsername(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        String username=request.getParameter("username");
        UserService userService=new UserService();
        boolean isExist=userService.isExist(username);
        String json="{\"isExist\":"+isExist+"}";
        response.getWriter().write(json);
    }

    public  void loginOut(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session=request.getSession();
        session.invalidate();
        response.sendRedirect("index.jsp");
    }
}
